﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BP.DA;
using System.Data;

namespace CCOA.App.Message
{
    public partial class RecycleBox : System.Web.UI.Page
    {
        #region //1.公共接口(Public Interface)
        //权限控制
        private string FuncNo = null;
        private void Alert(string msg)
        {
            BP.OA.Debug.Alert(this, msg);
        }
        private string CurUserNo
        {
            get { return BP.Web.WebUser.No; }
        }
        private void DeleteUseLessData()
        {
            //string sSql = "delete from OA_Message where OID not in (select FK_MsgNo from OA_InBox) and OID not in (select FK_MsgNo from OA_SendBox)";
            //BP.DA.DBAccess.RunSQL(sSql);
            BP.OA.Message.Message.DeleteUseLessData();
        }
        public string GetUserNames(object userNos)
        {
            String users = String.Format("{0}", userNos);
            return BP.OA.GPM.GetUserNames(users);
        }
        #endregion

        #region //2.页面装载(Page Load)
        protected void Page_Init(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (!BP.OA.GPM.IsCanUseFun(this.FuncNo)) { BP.OA.GPM.RedirectNoAccess(); return; }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Page.SetFocus(btnSearchByKey);
            if (!this.IsPostBack)
            {
                this.LoadData(true);
            }            
        }
        private void LoadData(bool start)
        {
            string con = null;
            string key = this.txtKeywords.Text.Trim();
            if (!String.IsNullOrEmpty(key))
            {
                con = String.Format(" and (Doc like '%{0}%' OR B.Title like '%{1}%')", key, key);
            }
            //需要返回列：No,Content,Geter,RPT
            //string sSql = String.Format("select OID as No,Doc as Content,AddTime as RPT,SendToUsers as Geter from  OA_Message where FK_UserNo='{0}' and MessageState=0 {1} order by OID desc", BP.Web.WebUser.No, con);

            string oldTimeTypeSql = "select AddTime from OA_MessageRecycleBox";
            DataTable dtNewTimeType = DBAccess.RunSQLReturnTable(oldTimeTypeSql);

            for (int i = 0; i < dtNewTimeType.Rows.Count; i++)
            {
                string newDateTime = BP.OA.Main.TransDateTime(dtNewTimeType.Rows[i]["AddTime"].ToString());
                string newTimeTypeSql = string.Format("update OA_MessageRecycleBox set AddTime='{0}' where AddTime='{1}'", newDateTime, dtNewTimeType.Rows[i]["AddTime"].ToString());
                DBAccess.RunSQL(newTimeTypeSql);

            }

            string sSql = String.Format("select A.OID as No,B.Title as Title,A.AddTime as RPT,A.FromType as FromType,A.FK_UserNo,B.AttachFile from OA_MessageRecycleBox A inner join OA_Message B on A.FK_MsgNo=B.OID where A.FK_UserNo='{0}' {1}", BP.Web.WebUser.No, con);

            if (start)
            {
                AspNetPager1.RecordCount = BP.OA.Main.GetPagedRowsCount(sSql);  //第一次需要初始化
                AspNetPager1.PageSize = BP.OA.Main.GetConfigItem("PageSize") == null ? 20 : Convert.ToInt32(BP.OA.Main.GetConfigItem("PageSize"));
                AspNetPager1.CurrentPageIndex = 1;
            }
            int total = DBAccess.RunSQLReturnCOUNT(sSql);
            int PageCount = total % (AspNetPager1.PageSize) == 0 ? total / (AspNetPager1.PageSize) : total / (AspNetPager1.PageSize) + 1;
            this.AspNetPager1.CustomInfoHTML = string.Format("当前第{0}/{1}页 共{2}条记录 每页{3}条", new object[] { this.AspNetPager1.CurrentPageIndex, PageCount, total, this.AspNetPager1.PageSize });

            //this.AspNetPager1.CustomInfoHTML = string.Format("当前第{0}/{1}页 共{2}条记录 每页{3}条", new object[] { this.AspNetPager1.CurrentPageIndex, this.AspNetPager1.PageCount, this.AspNetPager1.RecordCount, this.AspNetPager1.PageSize });
            this.gridData.DataSource = BP.OA.Main.GetPagedRows(sSql, 0, " Order by No desc", this.AspNetPager1.PageSize, this.AspNetPager1.CurrentPageIndex);
            //System.Data.DataTable dt = BP.DA.DBAccess.RunSQLReturnTable(sSql);
            //this.gridData.DataSource = dt;
            this.gridData.DataBind();
        }
        public string GetContentStr(object evalContent)
        {
            string s = String.Format("{0}", evalContent);
            if (!String.IsNullOrEmpty(s))
            {
                if (s.Length > 100)
                    s = s.Substring(0, 100) + "..";
            }
            return s;
        }
        public string GetFromType(object evalFromType)
        {
            int iFY = Convert.ToInt32(evalFromType);
            if (iFY == 0)
                return "草稿";
            else if (iFY == 1)
                return "发件";
            else
                return "收件";
        }
        #endregion

        #region //3.页面事件(Page Event)
        /// <summary>
        /// 根据关键字 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSearchByKey_Click(object sender, EventArgs e)
        {
            this.LoadData(true);
        }
        protected void btnEmptyBox_Click(object sender, EventArgs e)
        {
            //string sql = String.Format("Update OA_Message set MessageState=2 Where FK_UserNo='{0}' and MessageState=0", BP.Web.WebUser.No);
            string sql = String.Format("Delete FROM OA_MessageRecycleBox Where FK_UserNo='{0}';", BP.Web.WebUser.No);
            BP.DA.DBAccess.RunSQL(sql);
            this.DeleteUseLessData();
            this.LoadData(true);
        }

        protected void btnDeleteMsg_Click(object sender, EventArgs e)
        {
            string chkSel = this.Request.Form["chksel"];
            //string sql = String.Format("Update OA_Message set MessageState=2 Where FK_SendUserNo='{0}' and MessageState=0 and OID in ({1})", BP.Web.WebUser.No, chkSel);
            string sql = String.Format("Delete FROM OA_MessageRecycleBox Where FK_UserNo='{0}' and OID in ({1});", BP.Web.WebUser.No, chkSel);
            BP.DA.DBAccess.RunSQL(sql);
            this.DeleteUseLessData();
            this.LoadData(true);
        }
        protected void btnRestore_Click(object sender, EventArgs e)
        {
            string chkSel = this.Request.Form["chksel"];
            string[] id_list = chkSel.Split(new String[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            foreach (String id in id_list)
            {
                int i_id = Convert.ToInt32(id);
                BP.OA.Message.RecycleBox cb = new BP.OA.Message.RecycleBox();
                cb.OID = i_id;
                cb.RetrieveFromDBSources();

                BP.OA.Message.Message m = new BP.OA.Message.Message();
                m.OID = cb.FK_MsgNo;
                m.RetrieveFromDBSources();

                if (cb.FromType == 0)
                {
                    BP.OA.Message.DraftBox db = new BP.OA.Message.DraftBox();
                    db.AddTime = cb.AddTime;
                    db.FK_MsgNo = cb.FK_MsgNo;
                    db.FK_UserNo = cb.FK_UserNo;
                    db.InsertAsOID(cb.OID);
                }
                else if (cb.FromType == 1)
                {
                    BP.OA.Message.SendBox sb = new BP.OA.Message.SendBox();
                    sb.Receiver = m.SendToUsers;
                    sb.FK_MsgNo = cb.FK_MsgNo;
                    sb.FK_SendUserNo = m.FK_UserNo;
                    sb.SendTime = cb.AddTime;
                    sb.InsertAsOID(cb.OID);
                }
                else if (cb.FromType == 2)
                {
                    BP.OA.Message.InBox ib = new BP.OA.Message.InBox();
                    ib.FK_MsgNo = cb.FK_MsgNo;
                    ib.FK_ReceiveUserNo = cb.FK_UserNo;

                    if (string.IsNullOrEmpty(cb.ReceivedTime.ToString()))
                    {
                        ib.ReceiveTime = BP.OA.Main.CurDateTimeStr;
                    }
                    else
                    {
                        ib.ReceiveTime = String.Format("{0:yyyy-MM-dd HH:mm:ss}", cb.ReceivedTime);
                    }
                    ib.Received = cb.Received;
                    ib.AddTime = cb.AddTime;
                    ib.Sender = m.FK_UserNo;
                    ib.InsertAsOID(cb.OID);
                }
                cb.Delete();
                this.LoadData(true);
            }
            //string sql = String.Format("Update OA_Message set MessageState=2 Where FK_SendUserNo='{0}' and MessageState=0 and OID in ({1})", BP.Web.WebUser.No, chkSel);
            string sql = String.Format("Delete FROM OA_MessageRecycleBox Where FK_UserNo='{0}' and OID in ({1});", BP.Web.WebUser.No, chkSel);
            BP.DA.DBAccess.RunSQL(sql);
            this.DeleteUseLessData();
            this.LoadData(true);
        }
        protected void GridView1_DataBound(object sender, EventArgs e)
        {
            if (this.gridData.Rows.Count > 0)
                this.gridData.HeaderRow.TableSection = TableRowSection.TableHeader;
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            this.LoadData(false);
        }
        #endregion


    }
}